package com.aw.baselib.widgets;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.ProgressBar;

import com.aw.baselib.util.AwConvertUtil;
import com.aw.baselib.util.AwLog;

/**
 * @author : hzw
 * @date : 2021/8/12
 */
public class MyProgressView extends ProgressBar {

    private String text ;
    private Paint mPaint ;


    public MyProgressView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        init() ;
    }


    public MyProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        init() ;
    }


    public MyProgressView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        init() ;
    }

    @Override
    public synchronized void setProgress(int progress) {
        setText(progress);
        super.setProgress(progress);
    }

    @SuppressLint("ResourceAsColor")
    @Override
    protected synchronized void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        Rect rect = new Rect() ;
        mPaint.getTextBounds(text, 0, text.length(), rect) ;
//        int x = getWidth()/2 ;
//        int y = getHeight()/2;
        AwLog.d("===>getProgress: " + getProgress() + " ,getWidth(): " + getWidth() + " ,rect.centerX(): " + rect.centerX()
            + " ,rect.left: " + rect.left + " ,rect.right: " + rect.right
            + " ,百分比结果: " + (int) (getWidth() * AwConvertUtil.div(getProgress(), getMax(), 5)));
        int x = getWidth()/2 - rect.centerX() ;
        int y = getHeight()/2-rect.centerY() ;
        if(getProgress() > 10) {
            x = (int) (getWidth() * AwConvertUtil.div(getProgress(), getMax(), 5)) - rect.right - 20;
        }
        canvas.drawText(text, x, y, mPaint) ;
    }



    private void init(){
        mPaint = new Paint() ;
        mPaint.setTextSize(30f);
        mPaint.setColor(Color.BLACK) ;
    }


    public void setText(int progress){
        int i = (progress * 100)/this.getMax();
        this.text = i + "%";
    }
}
